#include "iapminimal.h"
#include "drmfile.h"
#include <QDebug>
#include <QApplication>
#include <QFile>
#include <QDir>

#define PRODUCTID "868627"
#define TICKETFOLDERNAME "tickets"
#define TICKETFNAME "868627.ticket"
#define REQUEST_STATUS_OK "OK"
#define REQUEST_STATUS_RESTORABLE "RestorableProduct"
#define RESOURCEFILE "/drm/data/resourceid_868627/myfile.dat"

const int KNonCryptedFileSize = 18;

IAPminimal::IAPminimal(QDeclarativeView *parent) :
    QObject(parent),
    purchstate(STATE_UNKNOWN),
    is2buy(false),
    iap_client(NULL)
{
    connect(parent, SIGNAL(statusChanged (QDeclarativeView::Status)), this, SLOT(statusChanged (QDeclarativeView::Status)));
}

void IAPminimal::statusChanged (QDeclarativeView::Status status)
{
    if(is2buy && status == QDeclarativeView::Ready){
        purchaseProduct();
    }
}

void IAPminimal::initIAP()
{
    if(iap_client)
        return;

    iap_client = new IAPClient(this);
    qRegisterMetaType<IAPClient::ProductDataHash>("IAPClient::ProductDataHash");
    connect(iap_client, SIGNAL(productDataReceived( int, QString, IAPClient::ProductDataHash)), this,
            SLOT(productDataReceived(int, QString, IAPClient::ProductDataHash)), Qt::QueuedConnection);
    connect(iap_client, SIGNAL(purchaseCompleted( int , QString, QString)), this,
            SLOT(purchaseCompleted( int , QString, QString)),Qt::QueuedConnection);
    connect(iap_client, SIGNAL(purchaseFlowFinished(int)), this, SLOT(purchaseFlowFinished(int)), Qt::QueuedConnection);
}

void IAPminimal::productDataReceived(int /*requestId*/, QString /*status*/, IAPClient::ProductDataHash /*productData*/)
{
    iap_client->purchaseProduct(PRODUCTID, IAPClient::ForcedAutomaticRestoration);
}

void IAPminimal::purchaseProduct()
{
    initIAP();
    iap_client->getProductData(PRODUCTID);
}

void IAPminimal::purchaseFlowFinished( int /*requestId*/ )
{
    if(purchstate == STATE_OK)
        emit productPurchaseComplete();
    else
        emit productPurchaseFailed();
}

void IAPminimal::purchaseCompleted( int /*requestId*/, QString status, QString purchaseTicket )
{
    if(status.length() == 0){
        purchstate = STATE_UNKNOWN;
    }else if ((status.compare(REQUEST_STATUS_OK, Qt::CaseSensitive) == 0) ||
              (status.compare(REQUEST_STATUS_RESTORABLE, Qt::CaseSensitive) == 0)) {
        setUnlocked(&purchaseTicket);
        purchstate = STATE_OK;
    }else{
        purchstate = STATE_FAILED;
    }
}

void IAPminimal::setUnlocked(QString *purchaseTicket)
{
    saveTicket(purchaseTicket);
}

bool IAPminimal::checkDRM()
{
    QString myfile(QApplication::applicationDirPath());
    myfile.append(RESOURCEFILE);

    if(QFile(myfile).size() == KNonCryptedFileSize)
        return false;

    DRMFile file;
    int error = file.open(myfile);
    file.close();
    return (error == KErrNone);
}

bool IAPminimal::isPurchased()
{
    return (checkDRM() || readTicket());
}

void IAPminimal::saveTicket(QString *purchaseTicket)
{
    if(!purchaseTicket)
        return;

    QString privatedir(getTicketDir());
    if(!QDir(privatedir).exists())
        QDir().mkdir(privatedir);

    QFile file(getTicketUri());
    if(file.open(QIODevice::WriteOnly))
    {
        QDataStream out(&file);
        out << *purchaseTicket;
        file.close();
    }
    else
    {
        qDebug() << "PurchasableItemBase::testModeSaveTicket >>> Cannot open file for writing: ";
    }
}

bool IAPminimal::readTicket()
{
    return (QFile(getTicketUri()).exists());
}

QString IAPminimal::getTicketUri()
{
    QString fname(getTicketDir());
    fname.append("/");
    fname.append(TICKETFNAME);
    return fname;
}

QString IAPminimal::getTicketDir()
{
    QString fname(QApplication::applicationDirPath());
    fname.append("/");
    fname.append(TICKETFOLDERNAME);
    return fname;
}
